package com.lhy.utilsdemo.websocket;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Liu Hangyu
 * @date 2021/12/11 15:29
 */
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("客户端发送的" + textWebSocketFrame.text());
        System.out.println(channelHandlerContext.channel().isActive());
        while (channelHandlerContext.channel().isActive()) {
            TimeUnit.SECONDS.sleep(1);
            Map map=new HashMap();
            map.put("1","666");
            TextWebSocketFrame resp = new TextWebSocketFrame("服务端响应数据");
            System.out.println(8);
            channelHandlerContext.channel().writeAndFlush(resp);
        }

    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().isActive());
        System.out.println("连接");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().isActive());
        ctx.channel().close();
        System.out.println("断开连接");
    }

}
